package com.hzqy.service.ift;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import com.graphbuilder.math.func.EFunction;
import com.hzqy.service.statistics.VisitServiceBean;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.LvYunUtil;
import com.hzqy.commons.utils.MD5Util;
import com.hzqy.commons.utils.XiRuanUtil;
import com.hzqy.commons.utils.SignUtil;
import com.hzqy.commons.utils.SystemConfigUtils;
import com.hzqy.persistence.dao.content.ContentDao;
import com.hzqy.persistence.dao.itf.HotelItfDao;
import com.hzqy.persistence.dao.product.ProductDao;
import com.hzqy.service.core.GenericServiceBean;
import com.hzqy.web.vo.CmContentVo;
import com.hzqy.web.vo.PmsOrgVo;
import com.hzqy.web.vo.StatDataAdvertisingStatisticsVo;
import com.hzqy.web.vo.SysProductVo;
import com.hzqy.web.vo.UserBillVo;


@Service
public class HotelItfServiceBean extends GenericServiceBean<PmsOrgVo, HotelItfDao, Integer> {

	private static final long serialVersionUID = 1L;
	protected final Logger LOG = LoggerFactory.getLogger(getClass());

	private ArrayList<CmContentVo> contentCache;
	@Resource
	private HotelItfDao hotelItfDao;
	@Resource
	private ProductDao productDao;
	@Resource
	private ContentDao contentDao;

	@Resource
	private VisitServiceBean visitServiceBean;

	@Override
	public HotelItfDao getEntityDao() {
		return hotelItfDao;
	}


	/**
	 * 拿到产品包价格
	 */
	public Map<String, Object> getProduct(String sign, String serverid, String timestamp, String secret, String source) {
		Map<String, Object> map = new HashMap<String, Object>();
		int resultCode = 0;
		String resultMsg = "";
		if (sign == null || serverid == null || timestamp == null || secret == null || source == null) {
			resultCode = 1001;//参数不全
			resultMsg = "参数不全";
		} else {
			String source_secret = SystemConfigUtils.getSysConfig(source + "_secret");
			Map<String, Object> signParams = new HashMap<String, Object>();
			LOG.debug("serverid：" + serverid);
			LOG.debug("timestamp：" + timestamp);
			LOG.debug("secret：" + source_secret);
			LOG.debug("source：" + source);
			signParams.put("serverid", serverid);
			signParams.put("timestamp", timestamp);
			signParams.put("secret", source_secret);
			signParams.put("source", source);
			String signStr = SignUtil.getSign(signParams, source_secret);
			LOG.debug("接收到的sign：" + sign);
			LOG.debug("本地获取的sign：" + signStr);
			LOG.debug("接收到的secret：" + secret);
			LOG.debug("本地获取的secret：" + source_secret);
			if (signStr.equals(sign) && source_secret.equals(secret)) {//验证成功
				PmsOrgVo org = hotelItfDao.selectOrgByContentId(serverid);
				resultCode = 1000;//成功
				resultMsg = "请求成功";
				Map<String, Object> message = new HashMap<String, Object>();
				message.put("serverid", serverid);
				if (org == null) {//账号没有对应的酒店
					int defaultProductId = Integer.valueOf(SystemConfigUtils.getSysConfig("defaultProductId"));
					SysProductVo productVo = productDao.selectProduct(defaultProductId);
					message.put("price", productVo.getF_sp_fee());
				} else {
					if (org.getF_po_price() == 0) {
						Map<String, Object> productMap = new HashMap<String, Object>();
						productMap.put("f_sp_priority", 1);
						productMap.put("f_spo_orgid", org.getF_po_id());
						List<SysProductVo> spList = productDao.selectProductList(productMap);
						if (spList.size() == 0) {//酒店没有对应的产品包
							int defaultProductId = Integer.valueOf(SystemConfigUtils.getSysConfig("defaultProductId"));
							SysProductVo productVo = productDao.selectProduct(defaultProductId);
							message.put("price", productVo.getF_sp_fee());
						} else {
							message.put("price", spList.get(0).getF_sp_fee());
						}
					} else {
						message.put("price", org.getF_po_price());
					}
					message.put("name", org.getF_po_name());
					message.put("address", org.getF_po_address());
					message.put("stars", org.getF_po_stars());
				}
				map.put("message", message);
			} else {
				resultCode = 1002;//参数错误
				resultMsg = "参数错误";
			}
		}
		map.put("resultCode", resultCode);
		map.put("resultMsg", resultMsg);
		return map;
	}


	public Map<String, Object> updateLDSHotetMessage(String message) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		HashMap<String, String> map = LvYunUtil.getLDSHotelMessage(message);
		if ("".equals(message)) {
			resultMap.put("rescode", "100");
			resultMap.put("resDesc", "数据为空");
			LOG.debug("接口信息为空");
		} else {
			resultMap.put("rescode", "200");
			resultMap.put("resDesc", "访问成功");
		}
		String orgId = map.get("orgId");
		if (map.get("bizType") != null && orgId != null) {
			String bizType = map.get("bizType").toString();
			String oldRmno = map.get("oldRmno");
			if ("RMCHG".equals(bizType) && StringUtils.isNotEmpty(oldRmno)) {//清空原本房间的入住信息
				Map<String, Object> clearMap = new HashMap<String, Object>();
				clearMap.put("firstResult", 0);
				clearMap.put("maxResults", 1);
				clearMap.put("f_cc_status", 1);
				clearMap.put("f_cc_companyid", orgId);
				clearMap.put("f_cc_type", 100);
				clearMap.put("f_cc_obligate1", oldRmno);
				List<CmContentVo> clearResults = contentDao.findContentList(clearMap);
				if (!clearResults.isEmpty()) {
					//CmContentVo content = clearResults.get(0);
					for (CmContentVo content : clearResults) {
						content.setF_cc_obligate2("");
						retryUpdate(content, 5);
						LOG.debug("换房：清空原房间号为" + oldRmno + ",账号为" + content.getF_cc_name() + " 成功");
					}
				}
			}

			Map<String, Object> cxMap = new HashMap<String, Object>();
			cxMap.put("firstResult", 0);
			cxMap.put("maxResults", 1);
			cxMap.put("f_cc_status", 1);
			cxMap.put("f_cc_companyid", orgId);
			cxMap.put("f_cc_type", 100);
			cxMap.put("f_cc_obligate1", map.get("rmno").toString());
			List<CmContentVo> results = contentDao.findContentList(cxMap);
			if (!results.isEmpty()) {
				//CmContentVo content = results.get(0);
				for (CmContentVo content : results) {
					if ("CHECKIN".equals(bizType) || "RMCHG".equals(bizType)) {//入住 || 换房
						if (content.getF_cc_obligate2() != null && (LvYunUtil.decode(content.getF_cc_obligate2()).indexOf("先生") > -1 || LvYunUtil.decode(content.getF_cc_obligate2()).indexOf("女士") > -1)) {
							content.setF_cc_obligate2(content.getF_cc_obligate2() + "," + map.get("name"));
						} else {
							content.setF_cc_obligate2(map.get("name"));
						}
						retryUpdate(content, 5);
						LOG.debug("修改内容id：" + content.getF_cc_id() + "账号：" + content.getF_cc_name() + "组织名：" + content.getF_cc_companyname() + ",房间号：" + content.getF_cc_obligate1() + "，姓名为：" + content.getF_cc_obligate2());
					} else if ("CHECKOUT".equals(bizType)) {//退房
						content.setF_cc_obligate2("");
						retryUpdate(content, 5);
						LOG.debug("修改内容id：" + content.getF_cc_id() + "账号：" + content.getF_cc_name() + "组织名：" + content.getF_cc_companyname() + ",房间号：" + content.getF_cc_obligate1() + "，姓名为：" + content.getF_cc_obligate2());
					} else {
						LOG.debug("类型为" + bizType + ",不处理");
					}
				}
			} else {
				LOG.debug("未查到符合条件的账号,组织id：" + orgId + ",房间号：" + map.get("rmno").toString());
			}
		}
		return resultMap;
	}

	public Map<String, Object> updateXRHotetMessage(String message) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		HashMap<String, String> map = XiRuanUtil.getXRHotelMessage(message);
		LOG.debug("解析结果为：" + map);
		if ("".equals(message)) {
			resultMap.put("rescode", "100");
			resultMap.put("resDesc", "数据为空");
			LOG.debug("接口信息为空");
		} else {
			resultMap.put("rescode", "200");
			resultMap.put("resDesc", "访问成功");
		}
		String orgId = map.get("orgId");
		String roomno = map.get("roomno");
		if (map.get("sta") != null && orgId != null && roomno != null && !"".equals(roomno)) {
			String oldRoomno = map.get("oldRoomno");
			if (StringUtils.isNotEmpty(oldRoomno)) {//清空原本房间的入住信息
				Map<String, Object> clearMap = new HashMap<String, Object>();
				clearMap.put("firstResult", 0);
				clearMap.put("maxResults", 1);
				clearMap.put("f_cc_status", 1);
				clearMap.put("f_cc_companyid", orgId);
				clearMap.put("f_cc_type", 100);
				clearMap.put("f_cc_obligate1", oldRoomno);
				List<CmContentVo> clearResults = contentDao.findContentList(clearMap);
				if (!clearResults.isEmpty()) {
					for (CmContentVo content : clearResults) {
						//CmContentVo content = clearResults.get(0);
						content.setF_cc_obligate2("");
						contentDao.updateContent(content);
						//retryUpdate(content, 5);
						LOG.debug("换房：清空原房间号为" + oldRoomno + ",账号为" + content.getF_cc_name() + " 成功");
					}
				}
			}

			String sta = map.get("sta").toString();
			Map<String, Object> cxMap = new HashMap<String, Object>();
			cxMap.put("firstResult", 0);
			cxMap.put("maxResults", 10);
			cxMap.put("f_cc_status", 1);
			cxMap.put("f_cc_companyid", orgId);
			cxMap.put("f_cc_type", 100);
			cxMap.put("f_cc_obligate1", map.get("roomno").toString());
			List<CmContentVo> results = contentDao.findContentList(cxMap);
			if (!results.isEmpty()) {
				for (int i = 0; i < results.size(); i++) {
					CmContentVo content = results.get(i);
					if ("I".equals(sta)) {//入住
						if (content.getF_cc_obligate2() != null && !"".equals(content.getF_cc_obligate2()) && content.getF_cc_obligate2().length() > 0) {
							content.setF_cc_obligate2(content.getF_cc_obligate2() + "," + map.get("name"));
						} else {
							content.setF_cc_obligate2(map.get("name"));
						}
						contentDao.updateContent(content);
						LOG.debug("修改内容id：" + content.getF_cc_id() + ",账号：" + content.getF_cc_name() + "组织名：" + content.getF_cc_companyname() + ",房间号：" + content.getF_cc_obligate1() + "，姓名为：" + content.getF_cc_obligate2());
					} else if ("O".equals(sta) || "S".equals(sta)) {//S：挂账退房 O：本日结账 D：昨日结账
						content.setF_cc_obligate2("");
						contentDao.updateContent(content);
						LOG.debug("修改内容id：" + content.getF_cc_id() + ",账号：" + content.getF_cc_name() + "组织名：" + content.getF_cc_companyname() + ",房间号：" + content.getF_cc_obligate1() + "，姓名为：" + content.getF_cc_obligate2());
					} else {
						LOG.debug("类型为" + sta + ",不处理");
					}
				}
			} else {
				LOG.debug("未查到符合条件的账号,组织id：" + orgId + ",房间号：" + map.get("roomno").toString());
			}
		}
		return resultMap;
	}

	public Map<String, Object> demandUserRecord(JSONObject object) {
		int flag = 0;
		Map<String, Object> resultMap = new HashMap<>();
		String account = object.getString("account");
		String productId = object.getString("productId");
		String productName = object.getString("productName");
		String totalFee = object.getString("totalFee");
		String orderSeq = object.getString("orderSeq");
		String orderTime = object.getString("orderTime");
		String sign = object.getString("sign");

		String dbfc_productids = SystemConfigUtils.getSysConfig("dbfc_productids");
		String[] arr = dbfc_productids.split(",");
		boolean result = false;
		result = Arrays.asList(arr).contains(productId);
		if (result) {
			String localSign = MD5Util.MD5_32bit(productId + orderSeq + "jdItvPay2020");
			if (sign.equals(localSign)) {
				UserBillVo userBillVo = new UserBillVo();
				userBillVo.setF_ub_serverid(account);
				userBillVo.setF_ub_productid(Integer.parseInt(productId));
				userBillVo.setF_ub_type(10);
				userBillVo.setF_ub_fee(totalFee);
				userBillVo.setF_ub_info(productName);
				userBillVo.setF_ub_ordertime(orderTime);
				userBillVo.setF_ub_source(orderSeq);
				userBillVo.setF_ub_endtime("2099-12-31 23:59:59");
				userBillVo.setF_ub_unsubtime("");
				flag = hotelItfDao.insertUserBill(userBillVo);
				if (flag == 1) {
					resultMap.put("resultCode", 1001);
					resultMap.put("resultMessage", "成功");
				}
			} else {
				LOG.debug("sign不一致，第三方支付sign：" + sign + ",本地sign:" + localSign);
				resultMap.put("resultCode", 1002);
				resultMap.put("resultMessage", "sign不一致");
			}
		} else {
			LOG.error("产品code为" + productId + "，不能入库");
			resultMap.put("resultCode", 1004);
			resultMap.put("resultMessage", "产品code为" + productId + "，不能入库");
		}
		return resultMap;
	}

//	public Map<String, Object> advertisingDayStatistics(JSONObject object) {
//		Map<String, Object> resultMap = new HashMap<>();
//		try {
//			String date = object.getString("f_sdas_date");
//			String source = object.getString("f_sdas_source");
//			String timestamp = object.getString("timestamp");
//			String key = SystemConfigUtils.getSysConfig("gg_import_itf_key");
//			String localSign = MD5Util.MD5_32bit(date+timestamp+key);
//			if("countryside".equals(source)||"public".equals(source)){
//				String sign = object.getString("sign");
//				LOG.debug("本地sign："+localSign+",参数sign："+sign);
//				if(localSign.equals(sign)){
//					JSONArray dataArr = object.getJSONArray("datas");
//					int insertCount = 0;
//					for(int i=0;i<dataArr.size();i++){
//						StatDataAdvertisingStatisticsVo sdasVo = new StatDataAdvertisingStatisticsVo();
//						sdasVo.setF_sdas_date(date);
//						sdasVo.setF_sdas_source(source);
//
//						Object contentId = dataArr.getJSONObject(i).get("contentId");
//						if(contentId!=null){
//							sdasVo.setF_sdas_contentId(Integer.parseInt(contentId.toString()));
//						}
//						Object contentName = dataArr.getJSONObject(i).get("contentName");
//						sdasVo.setF_sdas_contentName(contentName.toString());
//						Object pv = dataArr.getJSONObject(i).get("pv");
//						sdasVo.setF_sdas_index_pv(Integer.parseInt(pv.toString()));
//						Object uv = dataArr.getJSONObject(i).get("uv");
//						sdasVo.setF_sdas_index_uv(Integer.parseInt(uv.toString()));
//						Object time = dataArr.getJSONObject(i).get("time");
//						sdasVo.setF_sdas_play_time(Integer.parseInt(time.toString()));
//						Object type = dataArr.getJSONObject(i).get("type");
//						sdasVo.setF_sdas_type(Integer.parseInt(type.toString()));
//
//						if(i==0){
//							int count = hotelItfDao.deleteAdvertisingDay(sdasVo);
//							LOG.debug("删除广告统计数据成功count="+count+",日期为"+date+",来源为"+source);
//						}
//						insertCount += hotelItfDao.insertAdvertisingDay(sdasVo);
//					}
//					LOG.debug("插入广告统计数据成功count="+insertCount+",日期为"+date+",来源为"+source);
//
//					resultMap.put("resultCode",1001);
//					resultMap.put("resultMessage","成功");
//				}else{
//					resultMap.put("resultCode",1002);
//					resultMap.put("resultMessage","sign不正确");
//				}
//			}else{
//				resultMap.put("resultCode",1002);
//				resultMap.put("resultMessage","平台信息错误");
//			}
//
//		} catch (Exception e) {
//			LOG.error(e.getMessage());
//			resultMap.put("resultCode",1002);
//			resultMap.put("resultMessage","接口异常");
//		}
//
//		return resultMap;
//	}
//
//	public List<StatDataAdvertisingStatisticsVo> exportAdvertisingDayData(StatDataAdvertisingStatisticsVo statDataAdvertisingStatisticsVo,String sign,String timestamp){
//		List<StatDataAdvertisingStatisticsVo> list = null;
//		String key = SystemConfigUtils.getSysConfig("gg_export_itf_key");
//		String localSign = MD5Util.MD5_32bit(statDataAdvertisingStatisticsVo.getF_sdas_date()+timestamp+key);
//		LOG.debug("本地sign："+localSign+",参数sign："+sign);
//		if(localSign.equals(sign)){
//			list = (List<StatDataAdvertisingStatisticsVo>)visitServiceBean.selectAdvertisingList(statDataAdvertisingStatisticsVo, 1, 100000).get("rows");
//		}
//		return list;
//	}

	public void retryUpdate(CmContentVo content, int retryTimes) {
		try {
			contentDao.updateContent(content);
		} catch (Exception e) {
			LOG.debug("updateContent报错=" + e + "，开始重试" + retryTimes + "次");
			try {
				TimeUnit.SECONDS.sleep(1);
				if (retryTimes < 1) {
					contentCache.add(content);
					return;
				}
				retryUpdate(content, retryTimes - 1);
			} catch (InterruptedException ex) {
				ex.printStackTrace();
			}
		}
	}

	@Scheduled(cron = "0 0/5 * * * ?")
	private void configureTasks() {
		LOG.debug("sjdks");
		if (contentCache.size() > 0) {
			//如果缓存区有未更新的内容
			Iterator<CmContentVo> iter = contentCache.iterator();
			while (iter.hasNext()) {
				CmContentVo vo = iter.next();
				try {
					contentDao.updateContent(vo);
					iter.remove();
				} catch (Exception e) {
					//未更新成功
				}
			}
		}

	}
}
